package cn.tedu.sp06.filter;

import cn.tedu.web.util.JsonResult;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
@Slf4j
public class AccessFilter extends ZuulFilter {
    //过滤器的类型 pre,routing,post,error
    @Override
    public String filterType() {
        return FilterConstants.POST_TYPE;
    }
    //顺序号
    // zuul有5个默认的过滤器，
    // 在第5个过滤器中，向上下文对象添加了 serviceId 属性
    // 后面的过滤器才能访问 serviceId
    @Override
    public int filterOrder() {
        return 6;
    }
    //判断当前请求,是否要执行过滤代码
    //请求商品要检查权限,请求用户和订单不检查权限
    @Override
    public boolean shouldFilter() {
        //判断当前调用的后台服务,是不是item-service

        //获得调用的服务id
        RequestContext ctx = RequestContext.getCurrentContext();
        String serviceId = (String) ctx.get(FilterConstants.SERVICE_ID_KEY);
        //如果id是item-service，返回true
        return "item-service".equals(serviceId);
    }
    //过滤代码
    @Override
    public Object run() throws ZuulException {
        // http://localhost:3001/item-service/u5y34?token=y44t34t
        //接受token
        RequestContext ctx  = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        String token = request.getParameter("token");
        //如果没有token,阻止继续调用,直接返回响应
        //null,"","   "
        if (StringUtils.isBlank(token)){
            //阻止继续调用
            ctx.setSendZuulResponse(false);

            //直接返回响应
            //JsonResult - {code:xx, msg:xx, data:null}
            String json = JsonResult.err().code(JsonResult.NOT_LOGIN).msg("Not login").toString();
            ctx.addZuulRequestHeader("Content-Type", "appliction/json;charset=UTF-8");
            ctx.setResponseBody(json);

        }
        //如果没有token, 阻止继续调用,直接返回响应(请登录.........)
        return "null";
    }
}
